﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStuctureStudy.Queues
{
    public class ArrayQueue<T>
    {
        private readonly int _maxSize;
        private readonly T[] _items;
        private int _count = 0;
        private int _header = 0;
        private int _tail;

        public ArrayQueue(int size)
        {
            _maxSize = size;
            _items = new T[size];
            _tail = _maxSize - 1;
        }

        public void EnQueue(T item)
        {
            if (this.IsFull())
            {
                throw new InvalidOperationException("队列已满");
            }

            if (_tail == _maxSize - 1)
            {
                _tail = -1;
            }

            _items[++_tail] = item;

            _count++;
        }

        public T DeQueue()
        {
            if (this.IsEmpty())
            {
                throw new InvalidOperationException("队列已空");
            }

            T item = _items[_header++];

            if (_header == _maxSize)
            {
                _header = 0;
            }

            _count--;

            return item;
        }

        public T Peek()
        {
            if (this.IsEmpty())
            {
                throw new InvalidOperationException("队列已空");
            }

            return _items[_header];
        }

        public bool IsFull()
        {
            return _count == _maxSize;
        }

        public bool IsEmpty()
        {
            return _count == 0;
        }
    }
}
